package com.dang.alex.servlet.order;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.json.JSONArray;
import org.json.JSONObject;

import com.dang.alex.model.CartItem;
import com.dang.alex.model.Order;
import com.dang.alex.model.ReceiveAddress;
import com.dang.alex.model.User;
import com.dang.alex.service.imp.ReceiveAddressServiceimp;
import com.dang.alex.service.imp.ServiceDAOFactory;


@WebServlet({ "/OrderServlet", "/order.do" })
public class OrderServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	public static final String METHOD_CONFIRM="0";
	public static final String METHOD_SUBMIT="1";
	public static final String METHOD_ADDRESS="2";
	public static final String METHOD_FINISH="3";
   
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String method=req.getParameter("method");
		HttpSession session=req.getSession();
		Map<Integer,CartItem> map=(Map<Integer,CartItem>) session.getAttribute("s_car");
		if(method!=null){
			switch(method){
			case OrderServlet.METHOD_CONFIRM:
				confirm(req,resp,map);
				break;
			case OrderServlet.METHOD_SUBMIT:
				submit(req,resp);
				break;
			case OrderServlet.METHOD_ADDRESS:
				address(req,resp);
				break;
			case OrderServlet.METHOD_FINISH:
				finish(req,resp);
				break;
			}
		}
	}
	private void finish(HttpServletRequest req, HttpServletResponse resp) {
		ReceiveAddress addr=new ReceiveAddress();
		Order order=new Order();
		HttpSession session=req.getSession();
		String receiveName=null;
		//String fullAddress=req.getParameter("fullAddress");
		String fullAddress = null;
		try {
			receiveName = new String((req.getParameter("receiveName")).getBytes("ISO-8859-1"),"utf-8"); 
			fullAddress = new String((req.getParameter("fullAddress")).getBytes("ISO-8859-1"),"utf-8");
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} 
		String postalCode=req.getParameter("postalCode");
		String mobile=req.getParameter("mobile");
		String phone=req.getParameter("phone");
		String addressId=req.getParameter("addressId");
		//获取用户ID
		int userId=((User)session.getAttribute("s_user")).getId();
		//获取购物车
		Map<Integer,CartItem> map=(Map<Integer,CartItem>) session.getAttribute("s_car");
		//如果购物车中无商品，返回/main/main.jsp
		if(map.isEmpty()){
			try {
				//req.getRequestDispatcher("/WEB-INF/view/order/order_ok.jsp").forward(req, resp);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		//将用户id赋给addr实例
		addr.setUserId(userId);
		addr.setFullAddress(fullAddress);
		addr.setReceiceName(receiveName);
		addr.setPostalCode(postalCode);
		addr.setPhone(phone);
		addr.setMobile(mobile);
		addr.setId(Integer.parseInt(addressId));
		
		//创建order实例并对其赋值
		order=new Order();
		order.setFullAddress(addr.getFullAddress());
		order.setUserId(userId);
		order.setMobile(addr.getMobile());
		order.setOrderDesc("desc demo");
		order.setOrderTime(System.currentTimeMillis());
		order.setPhone(addr.getPhone());
		order.setPostalCode(addr.getPostalCode());
		order.setReceiceName(addr.getReceiceName());
		order.setStatus(0);
		order.setTotalPrice(total(map));
		//通过dao将数据存入数据可中
		//保存地址到数据库
		ReceiveAddressServiceimp service=ServiceDAOFactory.getReceiveAddressServiceimp();
		try {
			if(service.findById(addr.getId())==null){
				service.sava(addr);
			}
			//保存订单信息导数据库
			ServiceDAOFactory.getOrderServiceImp().save(order);
			//清空购物车信息
			map.clear();
			session.setAttribute("s_car", map);
			req.setAttribute("orderId", order.getId());
			req.setAttribute("totalPrice", order.getTotalPrice());
			req.getRequestDispatcher("/WEB-INF/view/order/order_ok.jsp").forward(req, resp);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	private void address(HttpServletRequest req, HttpServletResponse resp) {
		int UserId=((User)req.getSession().getAttribute("s_user")).getId();
		List<ReceiveAddress> addrs;
		try {
			addrs=ServiceDAOFactory.getReceiveAddressServiceimp().findByUserId(UserId);
			JSONObject json=new JSONObject();
			JSONArray array=new JSONArray();
			for (ReceiveAddress receiveAddress : addrs) {
				//JSONObject json1=(JSONObject) JSON.to
				JSONObject jsonDetail=new JSONObject();
				jsonDetail.put("id", receiveAddress.getId());
				jsonDetail.put("userId", receiveAddress.getUserId());
				jsonDetail.put("fullAddress", receiveAddress.getFullAddress());
				jsonDetail.put("mobile", receiveAddress.getMobile());
				jsonDetail.put("phone", receiveAddress.getPhone());
				jsonDetail.put("postalCode", receiveAddress.getPostalCode());
				jsonDetail.put("receiveName", receiveAddress.getReceiceName());
				array.put(jsonDetail);
			}
			json.put("addrs", array);
			PrintWriter out=resp.getWriter();
			out.print(json.toString());
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
			
	}
	private void submit(HttpServletRequest req, HttpServletResponse resp) {
		try {
			req.getRequestDispatcher("/WEB-INF/view/order/address_form.jsp").forward(req, resp);
		}  catch (Exception e) {
			e.printStackTrace();
		}

	}
	private void confirm(HttpServletRequest req, HttpServletResponse resp, Map<Integer, CartItem> map) {
		req.setAttribute("totalDang", total(map));
		req.setAttribute("s_car", map);
		try {
			req.getRequestDispatcher("/WEB-INF/view/order/order_info.jsp").forward(req, resp);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
	@SuppressWarnings("static-access")
	private double total(Map<Integer, CartItem> map) {
		double totalPrice=0.0;
		for(Map.Entry<Integer, CartItem> entry: map.entrySet()){
			totalPrice +=entry.getValue().getNum()*entry.getValue().getPro().getDangPrice();
		}
		BigDecimal bd=new BigDecimal(totalPrice);
		BigDecimal bd1=bd.setScale(2,bd.ROUND_HALF_UP);
		return bd1.doubleValue();
	}

}
